package com.android.mvp;

import android.app.Activity;
import android.app.Application;
import android.content.Context;

import com.android.mvp.ui.MainActivity;
import com.android.mvp.util.MLog;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * Created by Administrator on 2016/9/7 0007.
 */
public class MyApplication extends Application {
    private static MyApplication sAppContext;
    private static MyApplication instance;
    private List<Activity> activityList = new LinkedList<Activity>();
    private static final String TAG = "MyApplication";

    // 单例模式中获取唯一的MyApplication实例
    public static synchronized MyApplication getInstance() {
        if (null == instance) {
            instance = new MyApplication();
        }
        return instance;
    }
    /**
     * 内存泄漏
     * */
    private RefWatcher refWatcher;
    public static RefWatcher getRefWatcher(Context context) {
        MyApplication application = (MyApplication) context.getApplicationContext();
        return application.refWatcher;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        sAppContext=this;
        initLeakCanary();


        initOkhttp();


    }

    private void initOkhttp() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LoggerInterceptor("TAG"))
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                //其他配置
                .build();

        OkHttpUtils.initClient(okHttpClient);

    }


    public static MyApplication getAppContext() {
        return sAppContext;
    }



    private void initLeakCanary() {
        if (BuildConfig.DEBUG) {
            refWatcher = LeakCanary.install(this);
        } else {
            refWatcher = installLeakCanary();
        }
    }
    /**
     * release版本使用此方法
     */
    protected RefWatcher installLeakCanary() {
        return RefWatcher.DISABLED;
    }















    // 遍历所有Activity并finish
    public void exitNoMain() {
        for (Activity activity : activityList) {
            if (activity instanceof MainActivity) {

            }else {
                activity.finish();
            }
        }
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        activityList.add(activity);
        MLog.v(TAG,"添加数据了");
    }

    // 添加Activity到容器中
    public void clearActivity() {
        activityList.clear();
    }
}
